package com.bootdo.collection.utils;
import com.bootdo.collection.dao.PictureSetDao;
import com.bootdo.collection.dao.SourceStationDao;
import com.bootdo.collection.domain.PictureDO;
import com.bootdo.collection.domain.PictureSetDO;
import com.bootdo.collection.domain.SourceStationDO;
import org.apache.http.HttpEntity;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.HttpClients;

import java.io.*;

public class ImageByteUtil {
    public static byte[] fetchContent(PictureDO pictureDO, String referValue) {
        InputStream input = null;
        ByteArrayOutputStream output = null;
        HttpClient httpclient = HttpClientPool.getHttpClient();
        HttpGet httpget = new HttpGet(pictureDO.getPictureUrl());
        httpget.setHeader("Referer", referValue);
        CloseableHttpResponse response = null;
        HttpEntity entity;
        try {
            response = (CloseableHttpResponse) httpclient.execute(httpget);
            entity = response.getEntity();
            if (response.getStatusLine().getStatusCode() >= 400) {
                throw new IOException("Got bad response, error code = " + response.getStatusLine().getStatusCode()
                        + " imageUrl: " + pictureDO.getPictureUrl());
            }
            if (entity != null) {
                input = entity.getContent();
                output = new ByteArrayOutputStream();
                byte[] buff = new byte[1024];
                int len;
                while ((len = input.read(buff,0,1024)) != -1){
                    output.write(buff,0,len);
                }
                return output.toByteArray();
            }
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }catch (Exception e){
            e.printStackTrace();
        } finally {
            try {
                if(response != null){
                    response.close();
                }
                if(input != null){
                    input.close();
                }
                if(output != null){
                    output.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }

        }
        return null;
    }
}


